package cn.nawang.ebeim.client.transfer;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URI;

/**
 * 向服务端发起查询
 * Created by GanJc on 2016/1/8.
 */
public class TransferQueryHandler extends SimpleChannelInboundHandler<HttpObject> {

    private static final Logger LOG = LoggerFactory.getLogger(TransferQueryHandler.class);

    private TransferObject obj;

    private String errorMsg = "";

    private boolean isSuccess;

    private boolean isConnect;

    private long uploadLength = 0l;

    public TransferQueryHandler(TransferObject obj) {
        this.obj = obj;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        isConnect = true;
        File file = new File(obj.getFilePath());
        QueryStringEncoder encoder = new QueryStringEncoder("query");
        encoder.addParam("dataId", obj.getDsId());
        encoder.addParam("signature", obj.getSignature());
        encoder.addParam("isBreak", "false");
        URI uriGet = new URI(encoder.toString());
        String uri = TransferAuthService.encryptUrl(uriGet.toASCIIString());
        HttpRequest request =
                new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);
        HttpHeaders.setContentLength(request, file.length());

        ctx.writeAndFlush(request);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpResponse) {
            HttpResponse response = (HttpResponse) msg;
            if (HttpResponseStatus.OK.equals(response.getStatus())) {
                uploadLength = response.headers().getContentLength(response);
                isSuccess = true;
                LOG.info("query success: {},{} byte" , obj,uploadLength);
            } else {
                errorMsg = "query failed: " + obj + ", errorMsg: " + response.headers().get("error");
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOG.info("query failed:" , cause);
        errorMsg = cause.getMessage();
        ctx.close();
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public boolean isConnect() {
        return isConnect;
    }

    public long getUploadLength() {
        return uploadLength;
    }

}
